package cn.wk.basic.controller;

import cn.wk.basic.utils.AjaxResult;
import cn.wk.basic.utils.FastDfsApiOpr;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;

@RestController
@RequestMapping("/fastdfs")
public class FastdfsController {
    @RequestMapping("/upload")
    public AjaxResult upLoad(MultipartFile file) throws IOException {
        System.out.println(file);
        //获取其名字
        String originalFilename = file.getOriginalFilename();
        //用FilenameUtils获取其后缀
        String extension = FilenameUtils.getExtension(originalFilename);
        //调用fastdfs工具类进行上传
        //先把文件转换成byte数组
        byte[] bytes = file.getBytes();
        //得到一个url地址
        String upload = FastDfsApiOpr.upload(bytes, extension);
        //返回给前台（这里面有图片的url地址）
        return new AjaxResult().setResultObj(upload);
    }

    @PostMapping("/uploadtest")
    public AjaxResult uploadTest(MultipartFile file) throws IOException {
        System.out.println(file);
        //获取文件的名字
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);
        //把传进来的文件转成byte数组
        byte[] fileBytes = file.getBytes();
        //获取后缀名(用工具类)
        String extension = FilenameUtils.getExtension(originalFilename);
        System.out.println(extension);

        //文件上传至fastdfs关键需要一个byte数组的文件和一个后缀名,返回一个上传路径名
        String upload = FastDfsApiOpr.upload(fileBytes, extension);
        System.out.println(upload);
        return new AjaxResult().setResultObj(upload);
    }
}
